using System.Net;
using System.Text.Json;
using MallApi.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace MallApi.Middlewares;

public class GlobalExceptionMiddleware
{
  private readonly RequestDelegate _next;
  private readonly ILogger<GlobalExceptionMiddleware> _logger;

  public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
  {
    _next = next;
    _logger = logger;
  }

  public async Task InvokeAsync(HttpContext context)
  {
    try
    {
      await _next(context);
    }
    catch (Exception ex)
    {
      await HandleExceptionAsync(context, ex);
    }
  }

  private async Task HandleExceptionAsync(HttpContext context, Exception exception)
  {
    context.Response.ContentType = "application/json";
    var apiResult = ApiResult<object>.Error(exception.Message, -1);

    var result = JsonSerializer.Serialize(apiResult);
    await context.Response.WriteAsync(result);
  }
}

public static class GlobalExceptionMiddlewareExtensions
{
  public static IApplicationBuilder UseGlobalExceptionMiddleware(this IApplicationBuilder builder)
  {
    return builder.UseMiddleware<GlobalExceptionMiddleware>();
  }
}